import React, { useState, useEffect } from "react";
import { Card, Tabs, List, Tag, Button, Space, Spin, message, Modal, Typography, Row, Col, Statistic, Alert } from "antd";
import {
  ClockCircleOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  SaveOutlined,
  SendOutlined,
  EyeOutlined,
  BookOutlined,
  CalendarOutlined,
  EnvironmentOutlined,
  FieldTimeOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import { studentAPI } from "../../../services/api";
import { useNavigate } from "react-router-dom";
import { useExamContext } from "../../../contexts/ExamContext";
import ExamDetailModal from "./components/ExamDetailModal";

const { Title, Text, Paragraph } = Typography;
const { confirm } = Modal;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ExamCard = styled(Card)`
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }
  
  .ant-card-body {
    padding: 20px;
  }
`;

const StudentExams: React.FC = () => {
  const navigate = useNavigate();
  const { 
    upcomingExams, 
    completedExams, 
    loading, 
    refreshExams,
    startExam: contextStartExam,
    getExamById 
  } = useExamContext();
  
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedExamId, setSelectedExamId] = useState<string>("");

  // 页面加载时刷新考试列表
  useEffect(() => {
    refreshExams();
  }, [refreshExams]);

  // 进入考试
  const handleEnterExam = (exam: any) => {
    if (exam.isInProgress) {
      // 如果考试正在进行中，直接进入
      navigate(`/student/exam-taking/${exam.id}`);
    } else {
      // 如果考试未开始，显示确认对话框
      confirm({
        title: "确认进入考试",
        content: (
          <div>
            <p>您即将进入考试：<strong>{exam.title}</strong></p>
            <p>考试时间：{exam.duration}分钟</p>
            <p>考试地点：{exam.location}</p>
            <Alert
              message="考试须知"
              description="进入考试后，系统将开始计时。请确保网络稳定，不要刷新页面或关闭浏览器。"
              type="warning"
              showIcon
              style={{ marginTop: 12 }}
            />
          </div>
        ),
        okText: "确认进入",
        cancelText: "取消",
        onOk: () => {
          // 开始考试并更新状态
          contextStartExam(exam.id);
          navigate(`/student/exam-taking/${exam.id}`);
        }
      });
    }
  };

  // 继续考试（针对进行中的考试）
  const handleContinueExam = (exam: any) => {
    confirm({
      title: "继续考试",
      content: (
        <div>
          <p>检测到您有未完成的考试：<strong>{exam.title}</strong></p>
          <p>剩余时间：{exam.duration}分钟</p>
          <Alert
            message="提示"
            description="系统将恢复您之前的答题进度，请继续完成考试。"
            type="info"
            showIcon
            style={{ marginTop: 12 }}
          />
        </div>
      ),
      okText: "继续考试",
      cancelText: "稍后继续",
      onOk: () => {
        navigate(`/student/exam-taking/${exam.id}`);
      }
    });
  };

  // 查看考试详情
  const handleViewExam = (examId: string) => {
    setSelectedExamId(examId);
    setDetailModalVisible(true);
  };

  // 关闭详情模态框
  const handleCloseDetailModal = () => {
    setDetailModalVisible(false);
    setSelectedExamId("");
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "未开始":
        return "blue";
      case "进行中":
        return "green";
      case "已完成":
        return "success";
      case "已结束":
        return "default";
      case "已提交":
        return "orange";
      default:
        return "default";
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case "闭卷":
        return "red";
      case "开卷":
        return "green";
      case "上机考试":
        return "blue";
      case "答辩":
        return "purple";
      default:
        return "default";
    }
  };

  const renderExamCard = (exam: any) => (
    <ExamCard key={exam.id}>
      <Row gutter={16} align="middle">
        <Col span={16}>
          <div style={{ marginBottom: 8 }}>
            <Space>
              <Title level={4} style={{ margin: 0 }}>
                {exam.title}
              </Title>
              <Tag color={getTypeColor(exam.type)}>{exam.type}</Tag>
              <Tag color={getStatusColor(exam.status)}>
                {exam.status}
              </Tag>
            </Space>
          </div>
          
          <div style={{ marginBottom: 8 }}>
            <Tag color="blue" icon={<BookOutlined />}>
              {exam.course}
            </Tag>
          </div>

          <Row gutter={16}>
            <Col span={8}>
              <Space>
                <CalendarOutlined />
                <Text>{exam.time}</Text>
              </Space>
            </Col>
            <Col span={8}>
              <Space>
                <FieldTimeOutlined />
                <Text>{exam.duration}分钟</Text>
              </Space>
            </Col>
            <Col span={8}>
              <Space>
                <EnvironmentOutlined />
                <Text>{exam.location}</Text>
              </Space>
            </Col>
          </Row>

          {exam.knowledgePoints && (
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">知识点：</Text>
              <Space wrap>
                {exam.knowledgePoints.slice(0, 3).map((point: string, index: number) => (
                  <Tag key={index}>{point}</Tag>
                ))}
                {exam.knowledgePoints.length > 3 && (
                  <Tag>+{exam.knowledgePoints.length - 3}</Tag>
                )}
              </Space>
            </div>
          )}

          {exam.score !== undefined && (
            <div style={{ marginTop: 8 }}>
              <Space>
                <Text strong>得分：</Text>
                <Text strong style={{ color: exam.score >= 90 ? '#52c41a' : exam.score >= 80 ? '#faad14' : '#ff4d4f' }}>
                  {exam.score}/{exam.fullScore}
                </Text>
              </Space>
            </div>
          )}

          {exam.submittedAt && (
            <div style={{ marginTop: 8 }}>
              <Text type="secondary">
                提交时间：{new Date(exam.submittedAt).toLocaleString()}
              </Text>
            </div>
          )}
        </Col>

        <Col span={8} style={{ textAlign: 'right' }}>
          <Space direction="vertical" size="small">
            {exam.isInProgress ? (
              <Button 
                type="primary" 
                danger
                icon={<ExclamationCircleOutlined />}
                onClick={() => handleContinueExam(exam)}
              >
                继续考试
              </Button>
            ) : exam.status === "未开始" || exam.status === "进行中" || exam.status === "已提交" ? (
              <Button 
                type="primary" 
                icon={<FileTextOutlined />}
                onClick={() => handleEnterExam(exam)}
              >
                {exam.status === "已提交" ? "继续考试" : "进入考试"}
              </Button>
            ) : null}
            
            <Button 
              icon={<EyeOutlined />}
              onClick={() => handleViewExam(exam.id)}
            >
              查看详情
            </Button>
          </Space>
        </Col>
      </Row>
    </ExamCard>
  );

  const items = [
    {
      key: "upcoming",
      label: "即将考试",
      children: (
        <div>
          {upcomingExams.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <Text type="secondary">暂无即将开始的考试</Text>
            </div>
          ) : (
            upcomingExams.map(renderExamCard)
          )}
        </div>
      ),
    },
    {
      key: "completed",
      label: "已完成考试",
      children: (
        <div>
          {completedExams.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <Text type="secondary">暂无已完成的考试</Text>
            </div>
          ) : (
            completedExams.map(renderExamCard)
          )}
        </div>
      ),
    },
  ];

  return (
    <div>
      <StyledCard title="考试中心">
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Statistic
              title="总考试数"
              value={upcomingExams.length + completedExams.length}
              prefix={<FileTextOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="即将考试"
              value={upcomingExams.filter(e => e.status === "未开始").length}
              valueStyle={{ color: "#1890ff" }}
              prefix={<ClockCircleOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="进行中"
              value={upcomingExams.filter(e => e.status === "进行中" || e.status === "已提交").length}
              valueStyle={{ color: "#52c41a" }}
              prefix={<CheckCircleOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="已完成"
              value={completedExams.length}
              valueStyle={{ color: "#52c41a" }}
              prefix={<CheckCircleOutlined />}
            />
          </Col>
        </Row>

        <Tabs items={items} />
      </StyledCard>

      <ExamDetailModal
        visible={detailModalVisible}
        examId={selectedExamId}
        onClose={handleCloseDetailModal}
      />
    </div>
  );
};

export default StudentExams;
